package hyj.qx.websocket.we;

import hyj.qx.websocket.service.ContentService;
import hyj.qx.websocket.service.Service.MessageBroadcaster;
import hyj.qx.websocket.service.Service.MessageRankService;
import hyj.qx.websocket.service.Service.OnlineUserService;
import hyj.qx.websocket.utils.GetHttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/websocket",configurator = GetHttpSession.class)
public class WebSocketServer {
    private static OnlineUserService onlineUserService;
    private static MessageRankService messageRankService;
    private static MessageBroadcaster broadcaster;
    private static Map<String,WebSocketServer> onlineUsers = new ConcurrentHashMap<>();
    private Session session;
    private String userName;
    private static ContentService contentService;
    @Autowired
    public void setContentService(ContentService service){
        contentService =service;
    }
    @Autowired
    public void setServices(OnlineUserService ous,
                            MessageRankService mrs,
                            MessageBroadcaster mb) {
        onlineUserService = ous;
        messageRankService = mrs;
        broadcaster = mb;
    }
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        this.session = session;
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.userName = (String) httpSession.getAttribute("user");
        onlineUserService.userLogin(this.userName);// 保存用户名
        onlineUsers.put(this.userName, this);
        broadcastAllUsers(getNames().toString());
        sendOnlineUsersUpdate();
    }


    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println(message);
        String[] parts = message.split(":", 2);
            String toUserName = parts[0]; // 第一个部分
            String content = parts[1];
            try{
           contentService.addContent(this.userName,toUserName,content);
           }catch (RuntimeException e){
                e.getStackTrace();
                System.out.println("数据库插入错误");
            }
        // 更新消息排行榜
        messageRankService.incrementMessageCount(this.userName);
        broadcaster.broadcast(message);
        WebSocketServer webSocketServer =onlineUsers.get(toUserName);
        webSocketServer.session.getBasicRemote().sendText(this.userName+":"+content);
    }
    @OnClose
    public void onClose(Session session) {
        onlineUsers.remove(this.userName);
        onlineUserService.userLogout(this.userName);
        String message = String.valueOf(getNames());
        sendOnlineUsersUpdate();
        broadcastAllUsers(message);
    }
    @OnError
    public void onError(Throwable error) {
        System.out.println("发生错误：" + error.getMessage());
    }
    private Set<String> getNames(){
        return onlineUsers.keySet();
    }
    private void broadcastAllUsers(String message){
        Set<String> names =onlineUsers.keySet();
        for(String name : names){
            WebSocketServer webSocketServer = onlineUsers.get(name);
            try {
                webSocketServer.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("当前用户在线"+names);
    }
    private void sendOnlineUsersUpdate() {
        Set<String> users = onlineUserService.getOnlineUsers();
        broadcaster.broadcast("ONLINE_USERS:" + String.join(",", users));
    }
}
